<template>
	<view>
		<view class="top" v-if="hasLogin">
			<view class="pad-20">
				<!-- #ifdef APP -->
				<uni-nav-bar :border="false" color="#222" backgroundColor="transparent" title="" />
				<!-- #endif -->
				<view class="flex" style="justify-content: space-between;">
					<view class="font-24 col-000-8">
						{{$t('mine.title')}}
					</view>
					<view class="font-14 col-000-4" v-if="userInfo._id" @click="logout">
						<!-- 退出登录 -->
						{{$t('settings.logOut')}}
					</view>
				</view>
				<view class="people-box">
					<view class="left">
						<view class="avatar">
							<cloud-image width="104rpx" height="104rpx"
								v-if="hasLogin&&userInfo.avatar_file&&userInfo.avatar_file.url"
								:src="userInfo.avatar_file.url"></cloud-image>
							<image v-else class="img-100" src="/static/images/avatar.png" mode="aspectFill"></image>
						</view>
					<view class="info">
						<view class="name font-18 col-000-8 font-600">
							{{userInfo.nickname}}
						</view>
						<view class="font-14 col-000-4">
							{{$t('mine.username')}}: {{userInfo.username}}
						</view>
					</view>
					</view>
					<view class="right">
						<view class="btn font-14 col-000-8" @click="toSettings">
							{{$t('mine.edit')}}
						</view>
					</view>
				</view>
				<!-- 我的收藏集 -->
				<MyCollectionSet />
				<!-- 语言设置 -->
				<view class="languagre-box" v-if="i18nEnable" @click="changeLanguage">
					<view class="left">
						<image class="img" src="/static/svg/languagre.svg" mode="widthFix"></image>
						<view class="font-14 col-000-8 font-500">
							{{$t('mine.changeLanguage')}}
						</view>
					</view>
					<view class="col-000-4 font-12">
						{{currentLanguage}}
					</view>
				</view>
				<!-- 我的收藏 -->
				<view class="my-collection" v-if="false">
					<view class="font-18 font-600 col-000-8">
						{{$t('mine.MyCollection')}}
					</view>
					<view class="list">
						<view class="item shadow" v-for="(item, index) in collectList" :key="index">
							<view class="t flex-center-center">
								<image class="img" src="/static/logo.png" mode="widthFix"></image>
							</view>
							<view class="b">
								<view class="name font-14 col-000-8">
									{{item.name}}
								</view>
								<view class="ico-collection">
									<uni-icons type="star" size="20"></uni-icons>
									<!-- <uni-icons type="star-filled" size="20"></uni-icons> -->
								</view>
							</view>
						</view>
					</view>
					<view class="empty-box" v-if="collectList.length == 0">
						<view class="">
							<view class="empty-img">
								<image class="img-100" src="/static/svg/empty.svg" mode="widthFix"></image>
							</view>
							<view class="empty-text">
								{{ $t('mine.noCollect') }}
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 添加收藏集 -->
			<addColecton ref="ref_addColecton" />
			<LanguageSet ref="ref_language_set" />
		</view>
		<view class="" v-if="!hasLogin">
			<view class="top">
			</view>
			<view class="">
				<view class="login-logo">
					<image class="img-100" :src="logo"></image>
				</view>
				<view class="font-14 col-000-8 m-t-8 text-center">
					<!-- 立即登录以使用全部功能 -->
					{{$t('userinfo.loginNow')}}
				</view>
				<view class="do-login col-fff font-14 font-500 flex-center-center" @click="doLogin">
					{{$t('mine.clickLogin')}}
				</view>
			</view>
		</view>
		<userInfoSetting ref="ref_user_setting" />
	</view>
</template>
<script>
	import userInfoSetting from '@/components/userinfo-setting/index.vue'
	import LanguageSet from '@/components/language-set/index.vue'
	import MyCollectionSet from '@/components/my-collection-set/index.vue'
	import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update';
	import callCheckVersion from '@/uni_modules/uni-upgrade-center-app/utils/call-check-version';
	import sandartApi from '@/api/index.js';
	// #ifdef APP
	import UniShare from '@/uni_modules/uni-share/js_sdk/uni-share.js';
	const uniShare = new UniShare()
	// #endif
	const db = uniCloud.database();
	import {
		store,
		mutations
	} from '@/uni_modules/uni-id-pages/common/store.js'

	import addColecton from './com-add-colection/index.vue'
	export default {
		data() {
			return {
				"logo": "/static/images/login-img.png",
				collectList: [{
					name: '雪山日出'
				}, {
					name: '雪山日出'
				}, {
					name: '雪山日出'
				}],
				currentLanguage: '',
				gridList: [{
						"text": this.$t('mine.showText'),
						"icon": "chat"
					},
					{
						"text": this.$t('mine.showText'),
						"icon": "cloud-upload"
					},
					{
						"text": this.$t('mine.showText'),
						"icon": "contact"
					},
					{
						"text": this.$t('mine.showText'),
						"icon": "download"
					}
				],
				ucenterList: [
					[
						// #ifdef APP-PLUS
						{
							"title": this.$t('mine.signInByAd'),
							"event": 'signInByAd',
							"icon": "compose"
						},
						// #endif
						{
							"title": this.$t('mine.signIn'),
							"event": 'signIn',
							"icon": "compose"
						},
						// #ifdef APP-PLUS
						{
							"title": this.$t('mine.toEvaluate'),
							"event": 'gotoMarket',
							"icon": "star"
						},
						//#endif
						{
							"title": this.$t('mine.readArticles'),
							"to": '/pages/ucenter/read-news-log/read-news-log',
							"icon": "flag"
						},
						{
							"title": this.$t('mine.myScore'),
							"to": '',
							"event": 'getScore',
							"icon": "paperplane"
						}
						// #ifdef APP
						, {
							"title": this.$t('mine.invite'),
							"event": 'share',
							"icon": "redo"
						}
						// #endif
					],
					[{
						"title": this.$t('mine.feedback'),
						"to": '/uni_modules/uni-feedback/pages/opendb-feedback/opendb-feedback',
						"icon": "help"
					}, {
						"title": this.$t('mine.settings'),
						"to": '/pages/ucenter/settings/settings',
						"icon": "gear"
					}],
					// #ifdef APP
					[{
						"title": this.$t('mine.about'),
						"to": '/pages/ucenter/about/about',
						"icon": "info"
					}]
					// #endif
				],
				listStyles: {
					"height": "150rpx", // 边框高度
					"width": "150rpx", // 边框宽度
					"border": { // 如果为 Boolean 值，可以控制边框显示与否
						"color": "#eee", // 边框颜色
						"width": "1px", // 边框宽度
						"style": "solid", // 边框样式
						"radius": "100%" // 边框圆角，支持百分比
					}
				}
			}
		},
		components: {
			addColecton,
			MyCollectionSet,
			LanguageSet,
			userInfoSetting
		},
		onLoad() {
			this.currentLanguage = uni.getStorageSync('CURRENT_LANG') == "en" ? 'English' : '简体中文'
		// 监听语言切换事件
			
			uni.$on("changeLanguage", (language) => {
				console.log("[UCENTER] 收到语言切换事件:", language)
				this.currentLanguage = language == "en" ? "English" : "简体中文"
				// 强制刷新页面以应用新语言
				this.$forceUpdate()
			})
		//#ifdef APP-PLUS
				this.ucenterList[this.ucenterList.length - 2].unshift({
					title: this.$t('mine.checkUpdate'), // this.this.$t('mine.checkUpdate')"检查更新"
					rightText: this.appVersion.version + '-' + this.appVersion.versionCode,
					event: 'checkVersion',
					icon: 'loop',
					showBadge: this.appVersion.hasNew
				})
				//#endif
	},
	onShow() {
		// 刷新用户信息,确保显示最新数据
		this.$forceUpdate()
		// 确保 TabBar 显示，防止从编辑资料返回后 TabBar 消失
		uni.showTabBar({
			animation: false
		});
	},
	onUnload() {
		// 移除监听器,避免内存泄漏
		uni.$off('changeLanguage')
	},
	computed: {
			userInfo() {
				return store.userInfo
			},
			hasLogin() {
				return store.hasLogin
			},
			// #ifdef APP-PLUS
			appVersion() {
				return getApp().appVersion
			},
			// #endif
			appConfig() {
				return getApp().globalData.config
			},
			i18nEnable() {
				return getApp().globalData.config.i18n.enable
			}
		},
		methods: {


			changeLanguage() {
				console.log('语言切换')
				this.$refs.ref_language_set.open()
				return
				// uni.showActionSheet({
				// 	itemList: ["English","简体中文"],
				// 	success: res => {
				// 		console.log(res); 
				// 		console.log(res.tapIndex); 
				// 		let language = uni.getStorageSync('CURRENT_LANG')
				// 		if(
				// 			!res.tapIndex && language=='zh-Hans' || res.tapIndex && language=='en'
				// 		){
				// 			const globalData = getApp().globalData
				// 			if (language === 'en') {
				// 				language = globalData.locale = 'zh-Hans'
				// 			} else {
				// 				language = globalData.locale = 'en'
				// 			}
				// 			uni.setStorageSync('CURRENT_LANG', language)
				// 			getApp().globalData.$i18n.locale = language
				// 			this.currentLanguage = res.tapIndex?'简体中文':'English'
				// 			if(uni.setLocale){
				// 				uni.setLocale(language)
				// 			}
				// 			uni.reLaunch({
				// 				url: '/pages/device/device',
				// 				complete: () => {
				// 					uni.$emit("changeLanguage",language)
				// 				}
				// 			})
				// 		}
				// 	},
				// 	fail: () => {},
				// 	complete: () => {}
				// });
			},
			logout() {
				uni.showModal({
					content: this.$t('settings.exitLogin'),
					cancelText: this.$t('settings.cancelText'),
					confirmText: this.$t('settings.confirmText'),
					success: (e) => {
						if (e.confirm) {
							mutations.logout()
						}
					}
				});

			},
			doLogin() {
				uni.navigateTo({
					url: '/uni_modules/uni-id-pages/pages/login/login-withpwd',
					complete: (e) => {
						// console.log(e);
					}
				})
			},
			toSettings() {
				// 延迟隐藏 TabBar，避免与弹窗动画冲突
				setTimeout(() => {
					uni.hideTabBar({
						animation: false
					});
				}, 50);
				this.$refs.ref_user_setting.open()
				// uni.navigateTo({
				// 	url: "/uni_modules/uni-id-pages/pages/userinfo/userinfo"
				// })
			},
			signIn() { //普通签到
				this.$refs.signIn.open()
			},
			signInByAd() { //看激励视频广告签到
				this.$refs.signIn.showRewardedVideoAd()
			},
			/**
			 * 个人中心项目列表点击事件
			 */
			ucenterListClick(item) {
				if (!item.to && item.event) {
					this[item.event]();
				}
			},

			async checkVersion() {
				let res = await callCheckVersion()
				console.log(res);
				if (res.result.code > 0) {
					checkUpdate()
				} else {
					uni.showToast({
						title: res.result.message,
						icon: 'none'
					});
				}
			},
			toUserInfo() {
				uni.navigateTo({
					url: '/uni_modules/uni-id-pages/pages/userinfo/userinfo'
				})
			},
			tapGrid(index) {
				uni.showToast({
					// title: '你点击了，第' + (index + 1) + '个',
					title: this.$t('mine.clicked') + " " + (index + 1),
					icon: 'none'
				});
			},
			/**
			 * 去应用市场评分
			 */
			gotoMarket() {
				// #ifdef APP-PLUS
				if (uni.getSystemInfoSync().platform == "ios") {
					// 这里填写appstore应用id
					let appstoreid = this.appConfig.marketId.ios; // 'id1417078253';
					console.log({
						appstoreid
					});
					plus.runtime.openURL("itms-apps://" + 'itunes.apple.com/cn/app/wechat/' + appstoreid + '?mt=8', err => {
						console.log('plus.runtime.openURL err:' + JSON.stringify(err));
					});
				}
				if (uni.getSystemInfoSync().platform == "android") {
					var Uri = plus.android.importClass("android.net.Uri");
					var uri = Uri.parse("market://details?id=" + this.appConfig.marketId.android);
					var Intent = plus.android.importClass('android.content.Intent');
					var intent = new Intent(Intent.ACTION_VIEW, uri);
					var main = plus.android.runtimeMainActivity();
					main.startActivity(intent);
				}
				// #endif
			},
			/**
			 * 获取积分信息
			 */
			getScore() {
				if (!this.userInfo) return uni.showToast({
					title: this.$t('mine.checkScore'),
					icon: 'none'
				});
				uni.showLoading({
					mask: true
				})
				db.collection("uni-id-scores")
					.where('"user_id" == $env.uid')
					.field('score,balance')
					.orderBy("create_date", "desc")
					.limit(1)
					.get()
					.then((res) => {
						console.log(res);
						const data = res.result.data[0];
						let msg = '';
						msg = data ? (this.$t('mine.currentScore') + data.balance) : this.$t('mine.noScore');
						uni.showToast({
							title: msg,
							icon: 'none'
						});
					}).finally(() => {
						uni.hideLoading()
					})
			},
			async share() {
				let {
					result
				} = await db.collection('uni-id-users').where("'_id' == $cloudEnv_uid").field('my_invite_code').get()
				let myInviteCode = result.data[0].my_invite_code
				if (!myInviteCode) {
					return uni.showToast({
						title: '请检查uni-config-center中uni-id配置，是否已启用 autoSetInviteCode',
						icon: 'none'
					});
				}
				console.log({
					myInviteCode
				});
				let {
					appName,
					logo,
					company,
					slogan
				} = this.appConfig.about
				// #ifdef APP
				uniShare.show({
					content: { //公共的分享类型（type）、链接（herf）、标题（title）、summary（描述）、imageUrl（缩略图）
						type: 0,
						href: this.appConfig.h5.url +
							`/#/pages/ucenter/invite/invite?code=uniInvitationCode:${myInviteCode}`,
						title: appName,
						summary: slogan,
						imageUrl: logo +
							'?x-oss-process=image/resize,m_fill,h_100,w_100' //压缩图片解决，在ios端分享图过大导致的图片失效问题
					},
					menus: [{
							"img": "/static/app/sharemenu/wechatfriend.png",
							"text": this.$t('common.wechatFriends'),
							"share": {
								"provider": "weixin",
								"scene": "WXSceneSession"
							}
						},
						{
							"img": "/static/app/sharemenu/wechatmoments.png",
							"text": this.$t('common.wechatBbs'),
							"share": {
								"provider": "weixin",
								"scene": "WXSceneTimeline"
							}
						},
						{
							"img": "/static/app/sharemenu/weibo.png",
							"text": this.$t('common.weibo'),
							"share": {
								"provider": "sinaweibo"
							}
						},
						{
							"img": "/static/app/sharemenu/qq.png",
							"text": "QQ",
							"share": {
								"provider": "qq"
							}
						},
						{
							"img": "/static/app/sharemenu/copyurl.png",
							"text": this.$t('common.copy'),
							"share": "copyurl"
						},
						{
							"img": "/static/app/sharemenu/more.png",
							"text": this.$t('common.more'),
							"share": "shareSystem"
						}
					],
					cancelText: this.$t('common.cancelShare'),
				}, e => { //callback
					console.log(e);
				})
				// #endif
			}
		}
	}
</script>
<style scoped lang="scss">
	.my-collection {
		width: 100%;
		margin-top: 80rpx;

		.list {
			width: 100%;
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-top: 40rpx;
			flex-wrap: wrap;

			.item {
				width: 314rpx;
				margin-bottom: 40rpx;

				.t {
					width: 100%;
					height: 314rpx;

					.img {
						width: 282rpx;
						height: 282rpx;
						border-radius: 100%;
					}
				}

				.b {
					padding: 24rpx 32rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
				}
			}
		}
	}

	.languagre-box {
		background: #FFFFFF;
		box-shadow: 0px 0px 8rpx 0px rgba(0, 0, 0, 0.08);
		border-radius: 16rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx 32rpx;
		margin-top: 80rpx;

		.left {
			display: flex;
			align-items: center;
			justify-content: flex-start;

			.img {
				width: 34rpx;
				height: 34rpx;
				margin-right: 18rpx;
			}
		}
	}

	.top {
		width: 100%;
		height: 500rpx;
		background: linear-gradient(180deg, #9ADBFB 0%, #FFFFFF 100%);
	}

	.people-box {
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 80rpx;

		.left {
			display: flex;
			justify-content: flex-start;
			align-items: center;
		}

		.info {
			margin-left: 16rpx;

			.name {
				margin-bottom: 8rpx;
			}
		}

		.right {
			.btn {
				width: 176rpx;
				height: 68rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				border-radius: 34rpx;
				border: 2rpx solid rgba(0, 0, 0, 0.8);
			}
		}
	}

	.avatar {
		width: 104rpx;
		height: 104rpx;
		overflow: hidden;
		border-radius: 100%;
	}

	.login-logo {
		width: 112rpx;
		height: 112rpx;
		margin: 0rpx auto 0;
	}

	.do-login {
		width: 670rpx;
		height: 100rpx;
		background: #000000;
		border-radius: 16rpx;
		margin: 80rpx auto 0;
	}
</style>